<?php
/**
 * jishupu-cms
 * @Author:技术铺<jishupu@qq.com>
 * @Date: 2021/11/11
 */

namespace App\Http\Controllers;

use App\Filters\PermissionFilter;
use App\Http\Requests\PermissionRequest;
use App\Http\Resources\PermissionCollection;
use App\Http\Resources\PermissionResource;
use App\Models\Permission;
use App\Services\CacheService;
use App\Services\PermissionService;
use App\Services\TreeService;
use Illuminate\Support\Facades\DB;

/**
 * 权限模块
 * Class PermissionController
 * @package App\Http\Controllers
 */
class PermissionController extends Controller
{

    /**
     * 列表
     * @param PermissionFilter $filter
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(PermissionFilter $filter)
    {
        $filter = Permission::filter($filter)->get();
        $collection = PermissionCollection::make($filter)->toArray(null);
        $items = TreeService::make($collection['items']);
        return $this->success('', ['items' => $items, 'total' => count($collection['items'])]);
    }

    /**
     * 添加
     * @param PermissionRequest $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Auth\Access\AuthorizationException
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(PermissionRequest $request)
    {
        $data = $request->validate('store');
        $permission = new Permission($data);
        if (!$permission->save()) return $this->errorStored();
        return $this->successStored();
    }

    /**
     * 查看
     * @param Permission $permission
     * @return \Illuminate\Http\JsonResponse
     */
    public function show(Permission $permission)
    {
        $permission = PermissionResource::make($permission)->only(['id', 'type', 'name', 'controller', 'priv', 'sort', 'public_type', 'description'])->toArray(null);
        return $this->success('', $permission);
    }

    /**
     * 更新
     * @param PermissionRequest $request
     * @param Permission $permission
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Auth\Access\AuthorizationException
     * @throws \Illuminate\Validation\ValidationException
     */
    public function update(PermissionRequest $request, Permission $permission)
    {
        $data = $request->validate('update');
        if (!$permission->update($data)) return $this->errorUpdated();
        return $this->successUpdated();
    }

    /**
     * 删除
     * @param Permission $permission
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy(Permission $permission)
    {
        DB::beginTransaction();
        try {
            $sub = Permission::where('parent_id', '=', $permission->id)->first();
            // 存在下级则禁止删除
            if ($sub) {
                return $this->error(__('permission.prohibit_delete_with_subs'));
            }
            $permission->delete();
            DB::commit();
            return $this->successDestoryed();
        } catch (\Exception $e) {
            DB::rollback();
            return $this->exception($e->getMessage())->errorDestoryed();
        }
    }

    /**
     * 更新状态
     * @param PermissionRequest $request
     * @param Permission $permission
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Auth\Access\AuthorizationException
     * @throws \Illuminate\Validation\ValidationException
     */
    public function updateStatus(PermissionRequest $request, Permission $permission)
    {
        $data = $request->validate('updateStatus');
        if (!$permission->update($data)) return $this->errorUpdated();
        return $this->successUpdated();
    }

    /**
     * 更新排序
     * @param PermissionRequest $request
     * @param Permission $permission
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Auth\Access\AuthorizationException
     * @throws \Illuminate\Validation\ValidationException
     */
    public function updateSort(PermissionRequest $request, Permission $permission)
    {
        $data = $request->validate('updateSort');
        if (!$permission->batchUpdate($data['sort'])) return $this->errorUpdated();
        return $this->successUpdated();
    }

    /**
     * 批量添加
     * @return \Illuminate\Http\JsonResponse
     */
    public function patchStore()
    {
        DB::beginTransaction();
        try {
            CacheService::clearRouteCache();
            $is_update = PermissionService::patchStore();
            DB::commit();
            return $this->success($is_update ? __('permission.success_done') : __('common.success_done'));
        } catch (\Exception $e) {
            DB::rollback();
            return $this->exception($e->getMessage())->error(__('common.error_done'));
        }
    }

    /**
     * 获取菜单模块等所需权限树数据
     * @return \Illuminate\Http\JsonResponse
     */
    public function menuPermissionTreeConfig()
    {
        $permission = Permission::select('id', 'parent_id', 'name', 'priv')->orderBy('sort', 'asc')->orderBy('id', 'desc')->get()->toArray();
        $result = TreeService::make($permission);
        return $this->success('', ['items' => $result]);
    }


}
